package com.leyantech.ecp.agenx.web.filter;

import com.leyantech.ecp.agenx.common.service.StoreConfigService;
import com.leyantech.ecp.agenx.common.service.StoreHomeService;
import com.leyantech.ecp.agenx.web.AuthMessage;
import com.leyantech.storehome.ProductVersionInfo;

import com.google.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-16.
 */
@Slf4j
public class ProductionFilter implements AuthFilter {

  private final StoreHomeService storeHomeService;

  private final StoreConfigService storeConfigService;

  @Inject
  public ProductionFilter(StoreHomeService storeHomeService,
      StoreConfigService storeConfigService) {
    this.storeHomeService = storeHomeService;
    this.storeConfigService = storeConfigService;
  }

  @Override
  public boolean test(AuthMessage authMessage) {
    final String storeId = authMessage.getStoreId();
    final Optional<ProductVersionInfo> productVersionInfoOptional = storeHomeService
        .getProductVersionInfo(storeId);

    if (productVersionInfoOptional.isPresent()) {
      if (!productVersionInfoOptional.get().getIsConnectable()) {
        log.info("filter by productVersion");
        return false;
      }
    } else {
      // 判断 店铺是否订阅等逻辑
      boolean subscribe = storeConfigService.isSubscribe(storeId);
      if (!subscribe) {
        log.warn("当前店铺没有订购服务, 或者已过期:{}, 不能被验证通过.", storeId);

        if (!storeConfigService.isLxkSubscribe(storeId)) {
          return false;
        }
        log.info("当前店铺仅订购lxk, args:{}", storeId);
      }
    }

    return true;
  }

}
